package com.maddox.maddoxppjoke;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.paging.DataSource;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;

//抽取数据加载的配置
public abstract class AbsViewModel<T> extends ViewModel {

    private final PagedList.Config config;
    private DataSource dataSource;
    private final LiveData<PagedList<T>> pageData;
    //监听是否有数据
    private MutableLiveData<Boolean> boundaryPageData = new MutableLiveData<>();

    public AbsViewModel() {
        //配置PagedList
        config = new PagedList.Config.Builder()
                .setPageSize(10)
                .setInitialLoadSizeHint(12)
                .build();
        //数据加载配置,从数据加载池的取数据配置以及监听
        pageData = new LivePagedListBuilder(factory, config)
                .setInitialLoadKey(0)
                .setBoundaryCallback(callback)
                .build();

    }

    public LiveData<PagedList<T>> getPageData() {
        return pageData;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public MutableLiveData<Boolean> getBoundaryPageData() {
        return boundaryPageData;
    }

    //数据加载的边界回调
    PagedList.BoundaryCallback<T> callback = new PagedList.BoundaryCallback<T>() {
        @Override
        public void onZeroItemsLoaded() {
            //没有数据了
             boundaryPageData.postValue(false);

        }

        @Override
        public void onItemAtFrontLoaded(@NonNull T itemAtFront) {
            //有数据了
           boundaryPageData.postValue(true);
        }

        @Override
        public void onItemAtEndLoaded(@NonNull T itemAtEnd) {

        }
    };

    //数据加载池的创建工厂
    DataSource.Factory factory = new DataSource.Factory() {
        @NonNull
        @Override
        public DataSource create() {
            if (dataSource == null || dataSource.isInvalid()) {
                dataSource = createDataSource();
            }
            return dataSource;
        }
    };
    //数据加载池,提供PagedList的数据来源
    public abstract DataSource createDataSource();
}
